package view;

import model.User;
import service.UserService;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EmptyBorder;

public class MainFrame extends JFrame {
    private static final Font MENU_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    
    private User currentUser;
    private UserService userService;
    private JPanel contentPanel;
    private CardLayout cardLayout;
    private GradeAnalysisPanel gradeAnalysisPanel;
    
    public MainFrame(User currentUser) {
        this.currentUser = currentUser;
        this.userService = new UserService();
        initComponents();
        setupMenu();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1440, 900);
        setLocationRelativeTo(null);
    }
    
    private void initComponents() {
        // 创建主面板，使用 BorderLayout
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));  // 添加边距
        
        // 创建内容面板，使用 CardLayout
        cardLayout = new CardLayout();
        contentPanel = new JPanel(cardLayout);
        
        // 创建一个居中的包装面板
        JPanel centerWrapper = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        
        // 创建欢迎页面
        JPanel welcomePanel = createWelcomePanel();
        contentPanel.add(welcomePanel, "欢迎");
        
        // 所有角色都有的面板
        contentPanel.add(new PersonalInfoPanel(currentUser), "个人信息");
        
        // 根据用户角色添加相应面板
        if ("ADMIN".equals(currentUser.getRole())) {
            contentPanel.add(new UserManagementPanel(), "用户管理");
            contentPanel.add(new DepartmentManagementPanel(), "系部管理");
            contentPanel.add(new MajorManagementPanel(), "专业管理");
            contentPanel.add(new SubjectManagementPanel(), "课程管理");
            contentPanel.add(new ClassManagementPanel(), "班级管理");
            contentPanel.add(new StudentManagementPanel(), "学生管理");
            contentPanel.add(new GradeAnalysisPanel(currentUser), "成绩分析");
            contentPanel.add(new ClassroomManagementPanel(), "教室管理");
            contentPanel.add(new SchedulePanel(currentUser.getId(), "ADMIN"), "课程表管理");
        } else if ("TEACHER".equals(currentUser.getRole())) {
            contentPanel.add(new GradeInputPanel(currentUser), "成绩录入");
            contentPanel.add(new GradeAnalysisPanelTeacher(currentUser), "成绩分析");
            contentPanel.add(new StudentManagementPanel(), "学生档案");
            contentPanel.add(new SchedulePanel(currentUser.getId(), "TEACHER"), "我的课程表");
        } else if ("STUDENT".equals(currentUser.getRole())) {
            contentPanel.add(new PersonalGradePanel(currentUser), "我的成绩");
            contentPanel.add(new StudentProfilePanel(currentUser.getId()), "个人档案");
            contentPanel.add(new SchedulePanel(currentUser.getId(), "STUDENT"), "我的课表");
        }
        
        // 初始显示欢迎页面
        cardLayout.show(contentPanel, "欢迎");
        
        // 将内容面板添加到居中包装面板
        centerWrapper.add(contentPanel, gbc);
        
        // 将居中包装面板添加到主面板
        mainPanel.add(centerWrapper, BorderLayout.CENTER);
        
        // 将主面板添加到框架
        setContentPane(mainPanel);
    }
    
    private void setupMenu() {
        JMenuBar menuBar = new JMenuBar();
        
        // 根据用户角色创建菜单
        if ("ADMIN".equals(currentUser.getRole())) {
            addMenuItem(menuBar, "系统管理", new String[]{
                "用户管理", "系部管理", "专业管理", "课程管理", "班级管理", "学生管理", "教室管理"
            });
            addMenuItem(menuBar, "教务管理", new String[]{
                "成绩分析", "课程表管理"
            });
            
            // 管理员保留完整的个人中心菜单
            addPersonalMenu(menuBar, true);
            
        } else if ("TEACHER".equals(currentUser.getRole())) {
            // 修改教师菜单，添加课程表
            addMenuItem(menuBar, "教学管理", new String[]{
                "成绩录入", "成绩分析", "学生档案", "我的课程表"  // 添加课程表菜单项
            });
            addPersonalMenu(menuBar, true);
            
        } else if ("STUDENT".equals(currentUser.getRole())) {
            addMenuItem(menuBar, "学习管理", new String[]{
                "我的成绩", "个人档案", "我的课表"
            });
            addPersonalMenu(menuBar, false);
        }
        
        setJMenuBar(menuBar);
    }
    
    private void addMenuItem(JMenuBar menuBar, String menuName, String[] items) {
        JMenu menu = new JMenu(menuName);
        menu.setFont(MENU_FONT);  // 设置菜单字体
        
        for (String item : items) {
            JMenuItem menuItem = new JMenuItem(item);
            menuItem.setFont(MENU_FONT);  // 设置菜单项字体
            menuItem.addActionListener(e -> cardLayout.show(contentPanel, item));
            menu.add(menuItem);
        }
        menuBar.add(menu);
    }
    
    // 添加修改密码对话框方法
    private void showChangePasswordDialog() {
        JDialog dialog = new JDialog(this, "修改密码", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(30, 40, 30, 40));  // 增加边距
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);  // 增加组件间距
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 创建密码输入框
        JPasswordField oldPasswordField = new JPasswordField(20);
        JPasswordField newPasswordField = new JPasswordField(20);
        JPasswordField confirmPasswordField = new JPasswordField(20);
        
        // 设置组件大小和字体
        Dimension fieldSize = new Dimension(250, 30);  // 增加输入框大小
        oldPasswordField.setPreferredSize(fieldSize);
        newPasswordField.setPreferredSize(fieldSize);
        confirmPasswordField.setPreferredSize(fieldSize);
        
        oldPasswordField.setFont(CONTENT_FONT);
        newPasswordField.setFont(CONTENT_FONT);
        confirmPasswordField.setFont(CONTENT_FONT);
        
        // 添加到表单
        int row = 0;
        addFormField(formPanel, "原密码：", oldPasswordField, gbc, row++);
        addFormField(formPanel, "新密码：", newPasswordField, gbc, row++);
        addFormField(formPanel, "确认密码：", confirmPasswordField, gbc, row++);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));  // 增加按钮间距
        JButton saveButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");
        
        // 设置按钮大小和字体
        Dimension buttonSize = new Dimension(90, 32);  // 增加按钮大小
        saveButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
        
        // 添加按钮事件
        saveButton.addActionListener(e -> {
            String oldPassword = new String(oldPasswordField.getPassword());
            String newPassword = new String(newPasswordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            
            // 验证输入
            if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请填写所有密码字段！");
                return;
            }
            
            if (!newPassword.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(dialog, "新密码与确认密码不匹配！");
                return;
            }
            
            // 验证原密码
            if (!userService.verifyPassword(currentUser.getId(), oldPassword)) {
                JOptionPane.showMessageDialog(dialog, "原密码错误！");
                return;
            }
            
            // 更新密码
            if (userService.updatePassword(currentUser.getId(), newPassword)) {
                JOptionPane.showMessageDialog(dialog, "密码修改成功！");
                dialog.dispose();
            } else {
                JOptionPane.showMessageDialog(dialog, "密码修改失败！");
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.setSize(450, 300);  // 增加对话框大小
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void addFormField(JPanel panel, String label, JComponent field, 
            GridBagConstraints gbc, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.anchor = GridBagConstraints.EAST;
        JLabel jLabel = new JLabel(label);
        jLabel.setFont(CONTENT_FONT);
        panel.add(jLabel, gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.weightx = 1.0;  // 添加权重使输入框占据更多空间
        panel.add(field, gbc);
        gbc.weightx = 0.0;  // 重置权重
    }
    
    private void showPersonalInfo() {
        cardLayout.show(contentPanel, "个人信息");
    }
    
    private void handleLogout() {
        int choice = JOptionPane.showConfirmDialog(
            this,
            "确定要退出登录吗？",
            "退出确认",
            JOptionPane.YES_NO_OPTION
        );
        
        if (choice == JOptionPane.YES_OPTION) {
            dispose();
            try {
                new LoginFrame().setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    private JPanel createWelcomePanel() {
        JPanel welcomePanel = new JPanel(new GridBagLayout());
        welcomePanel.setBackground(Color.WHITE);
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(10, 0, 10, 0);
        
        // 欢迎标题
        JLabel titleLabel = new JLabel("欢迎使用成绩管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        welcomePanel.add(titleLabel, gbc);
        
        // 用户信息
        JLabel userLabel = new JLabel(String.format("当前用户：%s（%s）", 
            currentUser.getName(), getRoleDisplayName(currentUser.getRole())));
        userLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        welcomePanel.add(userLabel, gbc);
        
        // 根据角色显示不同的提示信息
        String tipText = getWelcomeTipsByRole(currentUser.getRole());
        JLabel tipsLabel = new JLabel(tipText);
        tipsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        welcomePanel.add(tipsLabel, gbc);
        
        return welcomePanel;
    }
    
    private String getRoleDisplayName(String role) {
        switch (role) {
            case "ADMIN": return "管理员";
            case "TEACHER": return "教师";
            case "STUDENT": return "学生";
            default: return role;
        }
    }
    
    private String getWelcomeTipsByRole(String role) {
        switch (role) {
            case "ADMIN":
                return "您可以管理用户、系部、专业、课程、班级等信息";
            case "TEACHER":
                return "您可以进行成绩录入、查看成绩分析、管理学生档案等操作";
            case "STUDENT":
                return "您可以查看个人成绩、课表和档案信息";
            default:
                return "";
        }
    }
    
    // 添加个人中心菜单的方法
    private void addPersonalMenu(JMenuBar menuBar, boolean showPersonalInfo) {
        JMenu personalMenu = new JMenu("个人中心");
        personalMenu.setFont(MENU_FONT);
        
        if (showPersonalInfo) {
            JMenuItem personalInfoItem = new JMenuItem("个人信息");
            personalInfoItem.setFont(MENU_FONT);
            personalInfoItem.addActionListener(e -> showPersonalInfo());
            personalMenu.add(personalInfoItem);
        }
        
        JMenuItem changePasswordItem = new JMenuItem("修改密码");
        JMenuItem logoutItem = new JMenuItem("退出登录");
        
        changePasswordItem.setFont(MENU_FONT);
        logoutItem.setFont(MENU_FONT);
        
        changePasswordItem.addActionListener(e -> showChangePasswordDialog());
        logoutItem.addActionListener(e -> handleLogout());
        
        personalMenu.add(changePasswordItem);
        personalMenu.addSeparator();
        personalMenu.add(logoutItem);
        
        menuBar.add(personalMenu);
    }
    
} 